<template>
    <view class="index_user">
        <div class="region_div">
            <div class="left">
                <picker :value="searchForm.areaKey" :range="options.area" range-key="areaName"
                    @change="(data) => pickerChange('area', data)">
                    <image class="icon_1" mode="aspectFit"
                        src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_8.png" />
                    <div class="txt">{{ searchForm.areaName }}</div>
                    <image class="icon_2" mode="aspectFit"
                        src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_7.png" />
                </picker>
            </div>
            <!-- <image class="right" mode="aspectFit"
                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_9.png" /> -->
        </div>
        <div v-if="deviceList.length">
            <div class="swiper_div">
                <swiper class="swiper_box" @change="deviceChange">
                    <swiper-item v-for="(li, key) in deviceList" :key="key">
                        <view class="swiper_item">
                            <div class="lis">
                                <div class="li">
                                    <div class="p_1">
                                        <image class="icon_1" mode="aspectFit"
                                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_15.png" />
                                        {{ li.name }}
                                    </div>
                                    <div class="p_2">
                                        <div class="yuan" :class="li.linkStatus=='online'?'':'yuan_red'">
                                        </div>
                                        <!-- 1在线，0离线 -->
                                        <div class="txt" :class="li.linkStatus=='online'?'':'txt_red'">
                                            {{li.linkStatus=='online'?"在线":"离线" }}</div>
                                        <!-- 1合闸  0断闸 -->
                                        <div class="txt" :class="li.switchStatus==1?'':'txt_red'">{{
                                            li.switchStatus==1?"合闸":"断闸" }}
                                        </div>
                                    </div>
                                </div>
                                <div class="li">
                                    <div class="p_3">{{ li.balance ? li.balance.toFixed(2) : 0 }}</div>
                                    <div class="p_4">剩余金额(元)</div>
                                </div>
                                <div class="li li_1">
                                    <div class="p_5">{{ li.consumption }}</div>
                                    <div class="p_4">总用电量(度)</div>
                                </div>
                                <div class="li li_1">
                                    <div class="p_5">{{ li.current }}</div>
                                    <div class="p_4">当前电流(安)</div>
                                </div>
                                <div class="li li_1">
                                    <div class="p_5">{{ li.voltage }}</div>
                                    <div class="p_4">当前功耗(瓦)</div>
                                </div>
                                <div class="li">
                                    <div class="p_5">{{ li.currentPlan }}
                                        <image class="icon_2" mode="aspectFit"
                                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_17.png" />
                                    </div>
                                    <div class="p_4">收费标准(元/度)</div>
                                </div>
                            </div>
                            <div class="time">更新时间{{ li.updateTime }}</div>
                        </view>
                    </swiper-item>
                </swiper>
                <div class="swiper_indicator">
                    <div class="li" :class="key == deviceIndex ? 'li_active' : ''" v-for="(li, key) in deviceList"
                        :key="key">
                    </div>
                </div>
            </div>
            <div class="tools_div">
                <div class="li" @click="openPay">
                    <image class="img" mode="aspectFit"
                        src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_11.png" />
                    <div class="p">缴费</div>
                </div>
                <div class="li" @click="meterReading">
                    <image class="img" mode="aspectFit"
                        src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_12.png" />
                    <div class="p">抄表</div>
                </div>
                <div class="li" @click="switchStatus(0)">
                    <image class="img" mode="aspectFit"
                        :src="deviceList[deviceIndex].switchStatus != 0 ? 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_13.png' : 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_60.png'" />
                    <div class="p">断闸</div>
                </div>
                <div class="li" @click="switchStatus(1)">
                    <image class="img" mode="aspectFit"
                        :src="deviceList[deviceIndex].switchStatus != 1 ? 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_14.png' : 'https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_59.png'" />
                    <div class="p">合闸</div>
                </div>
            </div>
            <div class="data_div">
                <div class="li">
                    <div class="p_1">用能分析</div>
                </div>
                <div class="li">
                    <div class="p_2">{{ deviceList[deviceIndex].statConsumption.total || 0 }}</div>
                    <div class="p_3">总用电量(度)</div>
                </div>
                <div class="li li_1">
                    <div class="p_4">{{ deviceList[deviceIndex].statConsumption.day || 0 }}</div>
                    <div class="p_3">今日用电(度)</div>
                </div>
                <div class="li li_1">
                    <div class="p_4">{{ deviceList[deviceIndex].statConsumption.week || 0 }}</div>
                    <div class="p_3">本周用电(度)</div>
                </div>
                <div class="li li_1">
                    <div class="p_4">{{ deviceList[deviceIndex].statConsumption.month || 0 }}</div>
                    <div class="p_3">本月用电(度)</div>
                </div>
            </div>
            <div class="echart_div">
                <div class="title">电量(度)
                    <div class="month">
                        <picker mode="date" fields="month" :end="maxTime"
                            @change="(data) => pickerChange('year_month', data)">
                            {{ `${deviceList[deviceIndex].timeArr[0]}年${deviceList[deviceIndex].timeArr[1]}月` }}
                            <image class="icon" mode="aspectFit"
                                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_16.png" />
                        </picker>
                    </div>
                </div>
                <l-echart class="echart_div_box" ref="echart_div"></l-echart>
            </div>
        </div>

        <view class="pub_nodata_3" v-if="deviceList.length == 0 && loadFinish">
            <div style="height:70vw"></div>
            暂无设备信息
        </view>

        <div class="pay_box" v-if="payData.show">
            <div class="pay_div">
                <div class="title">充值
                    <image @click="closePay" class="right" mode="aspectFit"
                        src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_57.png" />
                </div>
                <div class="plis">
                    <div class="li" :class="payData.price == li && payData.price_input == '' ? 'li_active' : ''"
                        v-for="(li, key) in priceList" :key="key" @click="payData.price = li">{{ li }}元</div>
                    <div class="li">
                        <input class="input" type="digit" @input="dealPrice()" v-model="payData.price_input"
                            placeholder="请输入">
                        元
                    </div>
                </div>
                <div class="wlis">
                    <div class="p">支付方式</div>
                    <div class="li" v-if="payData.type == 1">
                        <image class="icon" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_37.png" />
                        支付宝支付
                        <image class="right" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_49.png" />
                    </div>
                    <div class="li" v-if="payData.type == 2">
                        <image class="icon" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_38.png" />
                        微信支付
                        <image class="right" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_49.png" />
                    </div>
                </div>
                <div class="pub_btn" @click="toPay">确认支付</div>
                <div class="msg" v-if="payTxt != ''">{{ payTxt }}</div>
            </div>
        </div>
    </view>
</template>

<script>
import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
export default {
    components: { LEchart },
    data() {
        return {
            payData: {
                show: false,
                price: '',
                price_input: '',
                type: '',//1支付宝 2微信
            },
            priceList: [20, 50, 100, 200, 300],

            options: {
                area: [],//区域列表
            },
            searchForm: {
                areaId: '',//区域
                areaName: '全部',
                areaKey: 0,
            },
            loadFinish: false,
            deviceList: [],
            deviceIndex: 0,
            stat_consumption: '',

            timeArr: [0, 0],
            maxTime: '',

            feeRate: 0,
            payTxt: '',
        };
    },
    mounted() {
        let deviceType = getApp().globalData.deviceType;
        if (deviceType == 'mp-alipay') this.payData.type = 1;
        if (deviceType == 'mp-weixin') this.payData.type = 2;

        var today = new Date(); // 获取当前日期时间
        let month = today.getMonth() + 1;
        this.timeArr = [today.getFullYear(), `${month > 9 ? '' : '0'}${month}`];
        this.maxTime = `${today.getFullYear()}-${month > 9 ? '' : '0'}${month}`;

        this.initPage();
    },
    methods: {
        initPage() {
            this.getArea();
            this.getDeviceList();
            this.getFeeRate();
        },
        dealPrice() {
            // console.log(this.form.fixedCharge.unitPrice);usageThreshold
            let value = this.payData.price_input;
            // value = value.replace(/[^\d.]/g, "");//清除"数字"和"."以外的字符    
            value = value.replace(/^\./g, "");//验证第一个字符是数字而不是字符    
            value = value.replace(/\.{2,}/g, ".");//只保留第一个.清除多余的    
            value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
            value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数  
            setTimeout(() => {
                this.payData.price_input = value;
                this.$forceUpdate();
            }, 1);
        },

        // 获取折线图数据
        async getEchartData() {
            const info = this.deviceList[this.deviceIndex];
            const res = await this.$request.get(`mobile/customer/device/stat_month_consumption/${info.id}`, {
                date: `${info.timeArr[0]}-${info.timeArr[1]}`
            });
            if (res.code == 200) {
                let dataA = Object.keys(res.data);
                let dataB = Object.values(res.data);
                // console.log(dataA, dataB);

                setTimeout(() => {
                    this.initEcharts(dataA, dataB);
                }, 400);
            }
        },
        async initEcharts(dataA, dataB) {
            const chart = await this.$refs.echart_div.init(echarts);
            const option = {
                grid: {
                    left: '2%',
                    right: '2%',
                    bottom: '1%',
                    top: '10%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    triggerEvent: true,
                    axisLabel: {
                        interval: 'auto',
                        textStyle: {
                            color: '#333'
                        }
                    },
                    data: dataA,
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#BFBFBF'
                        }
                    },
                    axisTick: {
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: 'rgba(0, 0, 0, 0.15)'
                        }
                    },
                },
                series: [
                    {
                        data: dataB,
                        type: 'line',
                        showSymbol: true,
                        smooth: true,
                        lineStyle: {
                            color: '#3296FA',
                            width: 5
                        },
                        symbolSize: function (data) { // 自定义symbol大小函数
                            return 8; // 随机生成符合正态分布的大小值
                        },
                        itemStyle: {
                            color: '#3296FA' // 设置空心圆的边界色为白色
                        }
                    }
                ]
            };
            chart.setOption(option)
        },

        async getArea() {
            const res = await this.$request.get('mobile/customer/area', {});
            // console.log(res);
            if (res.code == 200) {
                let arr = [{ areaId: "", areaName: "全部" }];
                this.options.area = arr.concat(res.data || []);
                this.$forceUpdate();
            }
        },
        async getDeviceList() {
            if (this.deviceList.length == 0) {
                this.$comFun.openLoading();
            }
            const res = await this.$request.get('mobile/customer/device', {
                areaId: this.searchForm.areaId
            });
            // console.log(res);
            if (this.deviceList.length == 0) {
                this.$comFun.closeLoading();
            }

            this.loadFinish = true;
            this.deviceIndex = 0;
            if (res.code == 200 && res.data && res.data.length) {
                this.deviceList = res.data.map(li => {
                    return {
                        ...li,
                        timeArr: this.timeArr,
                    }
                });
                // console.log(this.deviceList);
                setTimeout(() => {
                    this.getEchartData();
                }, 500)
            } else {
                this.deviceList = [];
            }
        },
        deviceChange(e) {
            this.deviceIndex = e.detail.current;
            this.getEchartData();
        },
        pickerChange(type, e) {
            // console.log(type, e.detail.value);
            if (type == 'area') {
                this.searchForm.areaKey = e.detail.value;
                this.searchForm.areaId = this.options.area[e.detail.value].areaId;
                this.searchForm.areaName = this.options.area[e.detail.value].areaName;
                this.getDeviceList();
            }
            if (type == 'year_month') {
                this.deviceList[this.deviceIndex].timeArr = e.detail.value.split("-");
                this.getEchartData();
            }
        },

        switchStatus(status) {
            const info = this.deviceList[this.deviceIndex];
            if (info.switchStatus == status) {
                return;
            }
            if (info.linkStatus == 'offline') {
                this.$comFun.toast('设备离线状态不支持该操作');
                return;
            }
            const that = this;
            // "0":断闸，"1":合闸
            uni.showModal({
                title: '提示',
                content: `是否确定${status == 0 ? '断闸' : '合闸'}？`,
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading(`正在${status == 0 ? '断闸' : '合闸'}中`);
                        let res = await that.$request.put(`mobile/customer/device/switch/${info.id}`, {
                            status: String(status)
                        });
                        if (res.code == 200) {
                            setTimeout(() => {
                                that.$comFun.closeLoading();
                                that.$comFun.toast(`${status == 0 ? '断闸' : '合闸'}成功`);
                                that.deviceList[that.deviceIndex].switchStatus = status;
                            }, 3000)
                        } else {
                            that.$comFun.closeLoading();
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        },
        meterReading() {
            const info = this.deviceList[this.deviceIndex];
            if (info.linkStatus == 'offline') {
                this.$comFun.toast('设备离线状态不支持该操作');
                return;
            }
            const that = this;
            uni.showModal({
                title: '提示',
                content: `是否确定抄表？`,
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading(`正在抄表中`);
                        let res = await that.$request.put(`mobile/customer/device/meterReading/${info.id}`, {});
                        if (res.code == 200) {
                            setTimeout(() => {
                                that.$comFun.toast(`抄表成功`);
                                that.deviceList = [];
                                that.loadFinish = false;
                                setTimeout(() => {
                                    that.getDeviceList();
                                }, 1000)
                            }, 3000)
                        } else {
                            that.$comFun.closeLoading();
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        },

        openPay() {
            const info = this.deviceList[this.deviceIndex];
            if (info.linkStatus == 'offline') {
                this.$comFun.toast('设备离线状态不支持该操作');
                return;
            }
            this.payData.show = true;
        },
        closePay() {
            this.payData.show = false;
            this.payData.price = '';
            this.payData.price_input = '';
        },
        async getFeeRate() {
            const that = this;
            const res = await that.$request.get(`/mobile/customer/getFeeRate`, {});
            // console.log(res);
            if (res.code == 200) {
                this.feeRate = res.data?.fee_rate || 0;
                if (this.feeRate != 0) {
                    this.payTxt = `支付时需额外支付${this.feeRate * 100}%手续费。用户需支付${Math.round((100 + 100 * this.feeRate) * 100) / 100}元，商户入账100元`;
                }
            }
        },
        async toPay() {
            const that = this;
            let real_amount = this.payData.price_input ? this.payData.price_input : this.payData.price;
            if (!real_amount) {
                this.$comFun.toast('请选择充值金额');
                return;
            }
            real_amount = Number(real_amount);
            const fee_amount = Math.round(real_amount * this.feeRate * 100) / 100;
            const amount = Math.round((fee_amount + real_amount) * 100) / 100;
            that.closePay();
            if (this.payData.type == 2) {
                that.$comFun.openLoading();
                const wxLoginInfo = uni.getStorageSync('wxLoginInfo');
                if (wxLoginInfo) {
                    const res_1 = await that.$request.post('mobile/manager/order/wechatPay', {
                        amount: amount,
                        fee_amount: fee_amount,
                        real_amount: real_amount,
                        deviceId: this.deviceList[this.deviceIndex].id,
                        sub_appid: 'wx61da2bfe086af80f',
                        sub_openid: wxLoginInfo.openid
                    });
                    // console.log(res_1);
                    if (res_1.code == 200) {
                        const wechatInfo = res_1.data.wechatInfo;
                        wx.requestPayment({
                            timeStamp: wechatInfo.timeStamp,
                            nonceStr: wechatInfo.nonceStr,
                            package: wechatInfo.package,
                            signType: 'MD5',
                            paySign: wechatInfo.paySign,
                            success(res) {
                                // console.log(res);
                                that.getOrderStatus(res_1.data.orderInfo);
                            },
                            fail(err) {
                                that.$comFun.closeLoading();
                                that.$comFun.toast('支付取消');
                            }
                        })
                    } else {
                        that.$comFun.closeLoading();
                        that.$comFun.toast('获取支付信息失败,' + res_1.msg);
                    }
                } else {
                    that.$comFun.closeLoading();
                    that.$comFun.toast('登录失败');
                }
            }
        },
        async getOrderStatus(orderInfo) {
            const that = this;
            const res_2 = await that.$request.get(`mobile/manager/order/${orderInfo.id}/payStatus`, {});
            that.$comFun.closeLoading();
            if (res_2.code == 200) {
                that.$comFun.toast('支付成功');
                that.deviceList = [];
                that.loadFinish = false;
                setTimeout(() => {
                    that.getDeviceList();
                }, 1000)
            } else {
                that.$comFun.toast('获取支付信息失败,' + res_2.msg);
            }
        }
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/index.scss";
</style>
